package com.egao.common.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.system.entity.QsSchool;
import com.egao.common.module.system.entity.vo.QsSchoolVO;
import com.egao.common.module.system.mapper.QsSchoolMapper;
import com.egao.common.module.system.service.QsSchoolService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * QS洲国家学校服务接口实现类
 *
 * @author lym
 */
@Service
public class QsSchoolServiceImpl extends ServiceImpl<QsSchoolMapper, QsSchool> implements QsSchoolService {

    private final Integer raw = 0;

    @Override
    public List<QsSchool> listAll(Integer parentId) {
        return baseMapper.selectList(new QueryWrapper<QsSchool>()
                .eq(parentId != null, "parent_id", parentId)
                .orderByAsc("id")
        );
    }

    @Override
    public String getLabel(Integer id, List<QsSchool> qsSchoolList) {
        Stream<QsSchool> schoolStream = qsSchoolList.stream();
        return schoolStream.filter(school -> id.equals(school.getId())).findFirst().get().getName();
    }

    @Override
    public JsonResult treeAll() {
        List<QsSchool> listAll = listAll(null);

        List<QsSchoolVO> tree = new ArrayList<>();

        for (QsSchool qs: listAll) {
            if (raw.equals(qs.getParentId())) {
                tree.add(new QsSchoolVO(qs.getId(), qs.getName()));
//                listAll.remove(qs);
            }
        }

        for (QsSchoolVO first : tree) {
            List<QsSchoolVO> secondList = new ArrayList<>();
            for (QsSchool qs: listAll) {
                if (first.getValue().equals(qs.getParentId())) {
                    secondList.add(new QsSchoolVO(qs.getId(), qs.getName()));
//                    listAll.remove(qs);
                }
            }
            first.setChildren(secondList);
        }

        for (QsSchoolVO first : tree) {
            for (QsSchoolVO second : first.getChildren()) {
                List<QsSchoolVO> thirdList = new ArrayList<>();
                for (QsSchool qs: listAll) {
                    if (second.getValue().equals(qs.getParentId())) {
                        thirdList.add(new QsSchoolVO(qs.getId(), qs.getName()));
                    }
                }
                second.setChildren(thirdList);
            }
        }

        return JsonResult.ok().setData(tree);
    }

}
